package com.packagetracker.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageButton;

import com.packagetracker.R;

public class CustomImageButton extends ImageButton {
	
	private int blur;
	private int focus;
	private int press;
	private boolean isPressed;
	
	public CustomImageButton(final Context context) {
		super(context);
		throw new RuntimeException("Valid image resource IDs must be passed to this class via the XML parameters: ptracker:resourceNotFocused & ptracker:resourceFocused.");
	}
	
	public CustomImageButton(final Context context, final AttributeSet attributes) {
		super(context, attributes);
		this.init(attributes);
	}
	
	public CustomImageButton(final Context context, final AttributeSet attributes, final int defStyle) {
		super(context, attributes, defStyle);
		this.init(attributes);
	}
	
	@Override
	public boolean onTouchEvent(final MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			this.isPressed = true;
			this.invalidate();
		}
		else if (event.getAction() == MotionEvent.ACTION_UP) {
			this.isPressed = false;
			this.requestFocus();
			this.invalidate();
		}
		
		return super.onTouchEvent(event);
	}
	
	@Override
	public void onDraw(final Canvas canvas) {
		if (this.isPressed) {
			this.setImageResource(this.press);
		}
		else if (this.isFocused()) {
			this.setImageResource(this.focus);
		}
		else {
			this.setImageResource(this.blur);
		}
		
		super.onDraw(canvas);
	}
	
	private void init(final AttributeSet attributes) {
		final TypedArray array = this.getContext().obtainStyledAttributes(attributes, R.styleable.CustomImageButton);
		
		if (array.getString(R.styleable.CustomImageButton_blur) != null) {
			this.focus = array.getResourceId(R.styleable.CustomImageButton_focus, -1);
		}
		
		if (array.getString(R.styleable.CustomImageButton_focus) != null) {
			this.blur = array.getResourceId(R.styleable.CustomImageButton_blur, -1);
		}
		
		if (array.getString(R.styleable.CustomImageButton_press) != null) {
			this.press = array.getResourceId(R.styleable.CustomImageButton_press, -1);
		}
		
		if ((this.focus == -1) || (this.blur == -1) || (this.press == -1)) {
			throw new RuntimeException("Valid image resource IDs must be passed to this class via the XML parameters: ptracker:resourceNotFocused, ptracker:resourceFocused, & ptracker:resourcePressed.");
		}
	}
	
}